var table;
$(function() {
	$("#systemId.chosen-select").chosen();
	$("#queryDiv").bind("keydown", function(e) {
		var theEvent = e || window.event;
		var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
		if (code == 13) {
			$("#serach").click();
		}
	});
	// 表格
	table = $('#dataList').dataTable({
		"fnServerData" : function(sSource, aoData, fnCallback) {
			$.ajax({
				"dataType" : 'json',
				"type" : "POST",
				"url" : ctx + "/mgr/funcTree/ajaxList",
				"data" : {
					"draw" : aoData.draw,
					"currentResult" : aoData.start,
					"showCount" : aoData.length,
					"name" : $("#name").val()
				},
				"success" : fnCallback
			});
		},
		"aoColumns" : [ {
			"data" : "functionSourceId"
		}, {
			"data" : "sourceName"
		}, {
			"data" : "sourceUrl"
		}, {
            "data" : "orderCode"
        }, {
			"data" : "enableStatus"
		}, {
			"data" : "sourceName"
		} ],
		"fnRowCallback" : function(nRow, aData, iDisplayIndex) {
			$('td:eq(0)', nRow).html(iDisplayIndex + 1);
			if (aData.enableStatus == 0) {
				$('td:eq(4)', nRow).html('启用');
			} else {
				$('td:eq(4)', nRow).html('停用');
			}
			$('td:eq(5)', nRow).html(operateHtml(aData));
		}
	});

	/**
	 * 搜索
	 */
	$('#serach').click(function() {
		table.fnDraw();
	});
});

/**
 * 获取操作数据
 */
function operateHtml(aData) {
	if (aData.functionSourceId == '-1' || aData.functionSourceId == '0') {
		return "";
	}
	var operateHtml = '<a href="' + ctx + '/mgr/funcTree/editUI/' + aData.functionSourceId + '"><i class="fa text-navy">编辑</i></a>';
	if (aData.enableStatus == 1) {
		// 停用状态
		operateHtml += '&nbsp;&nbsp;<a href="#" onclick="modifyEnableStatus_(\'' + aData.functionSourceId + '\',\'0\')"><i class="fa text-navy">启用</i></a>'
	} else {
		operateHtml += '&nbsp;&nbsp;<a href="#" onclick="modifyEnableStatus_(\'' + aData.functionSourceId + '\',\'1\')"><i class="fa text-navy">停用</i></a>'
	}
	return operateHtml;
}

/**
 * 删除数据
 */
function delete_(id) {
	if (!window.confirm("确定删除吗?")) {
		return;
	}

	$.ajax({
		url : ctx + "/funcTree/delete/" + id,
		type : 'post',
		dataType : 'json',
		timeout : ajaxTimeout,
		error : function(json) {
			toastr.error("删除失败");
		},
		success : function(json) {
			if (json.isSuccess) {
				toastr.success(json.msg);
			} else {
				toastr.error(json.msg);
			}
			table.fnPageChange(getPageNum(table, true));
		}
	});
}

/**
 * 修改状态
 */
function modifyEnableStatus_(id, enableStatus) {
	var confirmStr = "确认启用此资源吗？";
	if ("1" == enableStatus) {
		confirmStr = "确认禁用此资源吗？";
	}
	if (!window.confirm(confirmStr)) {
		return;
	}

	$.ajax({
		url : ctx + "/mgr/funcTree/modifyEnableStatus/" + id + "/" + enableStatus,
		type : 'post',
		dataType : 'json',
		timeout : ajaxTimeout,
		error : function(json) {
			toastr.error("修改失败")
		},
		success : function(json) {
			if (json.isSuccess) {
				toastr.success(json.errorMSG)
			} else {
				toastr.error(json.errorMSG)
			}
			table.fnPageChange(getPageNum(table, false));
		}
	});
};